﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ModelBinding;
using SpessartiteTwitter.Data;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity.Infrastructure;
using System.Web.UI.HtmlControls;
using Error_Handler_Control;

namespace SpessartiteTwitter
{
    public partial class TweetDetails : System.Web.UI.Page
    {
        private int? tweetId;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
            }
            else
            {
                tweetId = int.Parse(Request.Params["TweetId"]);
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                this.PanelAddCommentBox.Visible = true;
            }
        }

        public object FormViewTweetDetails_GetItem([QueryString] int? tweetId)
        {
            if (tweetId == null)
            {
                ModelState.AddModelError("", "Selected tweet doesn't exit in the database anymore.");
                this.PanelAddCommentBox.Visible = false;
                this.TweetDetailsCommentsUpdatePanel.Visible = false;
                this.FormViewTweetDetails.Visible = false;
                return null;
            }

            var context = new TwitterEntities();
            try
            {
                tweetId = int.Parse(Request.Params["TweetId"]);
            }
            catch (Exception ex)
            {
                ErrorSuccessNotifier.AddErrorMessage(ex);
                return null;
            }
            Tweet currentTweet = context.Tweets.Include("AspNetUser").FirstOrDefault(t => t.TweetId == tweetId);

            return currentTweet;
        }

        protected void ButtonAddComment_Click(object sender, EventArgs e)
        {
            using (var context = new TwitterEntities())
            {
                string commentText = this.CommentText.Text;
                this.CommentText.Text = "";
                this.tweetId = int.Parse(Request.Params["TweetId"]);
                Tweet currentTweet = context.Tweets.FirstOrDefault(t => t.TweetId == this.tweetId);

                string userId = User.Identity.GetUserId().ToString();
                if (!string.IsNullOrEmpty(userId))
                {
                    if (!string.IsNullOrEmpty(commentText))
                    {
                        Comment comment = new Comment()
                        {
                            DatePosted = DateTime.Now,
                            TweetId = currentTweet.TweetId,
                            CommentText = commentText,
                            UserId = userId
                        };
                        try
                        {
                            context.Comments.Add(comment);
                            context.SaveChanges();
                            this.ListViewTweetComments.DataBind();
                        }
                        catch (Exception ex)
                        {
                            ErrorSuccessNotifier.AddErrorMessage(ex);
                            return;
                        }
                    }
                    else
                    {
                        ErrorSuccessNotifier.AddInfoMessage("Enter comment please.");
                        return;
                    }
                }
                else
                {
                    ErrorSuccessNotifier.ShowAfterRedirect = true;
                    ErrorSuccessNotifier.AddInfoMessage("Please login to write comment");
                    Response.Redirect("/Account/Login.aspx", false);
                }
            }
        }

        public IQueryable<Comment> ListViewTweetComments_GetData()
        {
            int tweetId;
            try
            {
                tweetId = int.Parse(Request.Params["TweetId"]);
            }
            catch (Exception ex)
            {
                return null;
            }

            var context = new TwitterEntities();
            Tweet currentTweet = context.Tweets.FirstOrDefault(t => t.TweetId == tweetId);
            if (currentTweet == null)
            {
                ErrorSuccessNotifier.ShowAfterRedirect = true;
                ErrorSuccessNotifier.AddInfoMessage("Tweet is missing");
                Response.Redirect("Default.aspx", false);
                return null;
            }

            var comments = currentTweet.Comments;
            return comments.AsQueryable()
                                .OrderByDescending(d => d.DatePosted);
        }

        protected void ListViewTweetComments_DataBound(object sender, EventArgs e)
        {
            var pager = this.DataPagerComments;
            pager.Visible = pager.TotalRowCount > pager.MaximumRows;
        }
    }
}